package com.gitee.feizns.web.ex.impl;

import com.gitee.feizns.web.domain.result.Ret;
import com.gitee.feizns.web.ex.CustomizeExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

/**
 * @author feizns
 * @since 2019/7/7
 */
public class MethodArgumentNotValidExceptionHandler implements CustomizeExceptionHandler<MethodArgumentNotValidException, Object> {

    @Override
    public ResponseEntity<Ret<Object>> handle(MethodArgumentNotValidException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Ret.err(HttpStatus.BAD_REQUEST.value(), getDefaultMessage(e.getBindingResult())));
    }

    private String getDefaultMessage(BindingResult e) {
        FieldError error = e.getFieldError();
        return error.getField() + " " + error.getDefaultMessage();
    }

}
